/****************************************************
文件：DSTask.cs
作者：UnitySir
邮箱：zouajck@foxmail.com
日期：2021/03/22 20:24:37
功能：Nothing
*****************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

namespace DSFramework
{
    public class DSTask
    {
        private CancellationTokenSource source = new CancellationTokenSource();

        public DSTask()
        {
        }

        public DSTask(Action action)
        {
            Run(action);
        }

        public DSTask(Action action, int time)
        {
            Run(action, time);
        }

        public void Run(Action action)
        {
            Task.Run(() =>
            {
                action?.Invoke();
                source.Token.ThrowIfCancellationRequested();
            }, source.Token);
        }

        public void Run(Action action, int time)
        {
            Task.Run(() =>
            {
                while (true)
                {
                    action?.Invoke();
                    Thread.Sleep(time);
                    source.Token.ThrowIfCancellationRequested();
                }
            }, source.Token);
        }

        public void Cancel()
        {
            source.Cancel();
        }
    }
}